package com.code.day21;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.UUID;

public class DemoFileServerClientDuo {
    public static void main(String[] args) throws Exception {
        //1.创建ServerSocket对象
        ServerSocket serverSocket = new ServerSocket(6666);

        while (true) {
            Socket socket = serverSocket.accept();
            new Thread(new Runnable() {
                @Override
                public void run() {
                    FileOutputStream fos = null;
                    InputStream inputStream = null;
                    OutputStream outputStream = null;
                    //2.调用accept方法,获取到客户端的Socket对象

                    String name = UUID.randomUUID().toString();

                    //3.创建FileOutputStream,用于将读取过来的图片写到本地上  此时还没有读 而是指定往哪里写
                    try {
                        fos = new FileOutputStream("D:\\java-code\\java-full-stack\\01-java-base\\src\\com\\code\\day21\\file\\" + name + ".jpg");
                        //4.调用Socket中的getInputStream,用于读取客户端发送过来的图片
                        inputStream = socket.getInputStream();
                        //5.边读边写
                        byte[] bytes = new byte[1024];
                        int len = 0;
                        while ((len = inputStream.read(bytes)) != -1) {
                            fos.write(bytes, 0, len);
                        }
                        System.out.println("==========以下代码是响应代码=========");
                        //6.获取getOutputStream,用于给客户端响应数据
                        outputStream = socket.getOutputStream();
                        outputStream.write("上传成功".getBytes());
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    CloseUtils.closeQ(outputStream, inputStream, fos, socket);
                    //7.关闭资源
                }
            }).start();
        }


    }

}
